package com.ask.server.handler;

import com.ask.common.constant.MessageConstant;
import com.ask.common.exception.BaseException;
import com.ask.common.result.Result;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException ex) {
        log.error("业务异常 [code={}]:{}", ex.getErrorCode(), ex.getMessage(), ex);
        return Result.error(ex.getErrorCode(), ex.getMessage());
    }

    @ExceptionHandler(MySQLIntegrityConstraintViolationException.class)
    public Result handleDuplicateKeyException(MySQLIntegrityConstraintViolationException ex) {
        log.error("数据库唯一约束冲突：{}", ex.getMessage(), ex);
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String name = split[2];
            String msg = name + MessageConstant.ALREADY_EXIST;
            return Result.error(msg);
        }
        else
            return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}
